package indi.h.security.signature;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;

import indi.h.security.Parameters;

public class SignatureVerification extends AbstractSV {
	protected SVParameter svParameter;
	protected PrivateKey privateKey;
	protected PublicKey publicKey;
	protected Sign sign;
	protected Verify verify;

	protected SignatureVerification() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		try {
			KeyPairGenerator kpg = KeyPairGenerator.getInstance(svParameter.getAlgorithm());
			if (svParameter.getSecureRandom() != null) {
				kpg.initialize(svParameter.getLength(),
						new SecureRandom(svParameter.getSecureRandom().getBytes(svParameter.getCode())));
			} else {
				kpg.initialize(svParameter.getLength());
			}
			KeyPair kp = kpg.generateKeyPair();
			publicKey = kp.getPublic();
			privateKey = kp.getPrivate();
			initSignature();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected void initSignature() {
		try {
			Signature signature = Signature.getInstance(svParameter.getSignAlgorithm());
			if (svParameter.getSignSecureRandom() != null) {
				byte[] b = svParameter.getSignSecureRandom().getBytes(svParameter.getCode());
				signature.initSign(privateKey, new SecureRandom(b));
				sign = new SignImp(signature, svParameter.getAlgorithm(), b);
			} else {
				signature.initSign(privateKey);
				sign = new SignImp(signature, svParameter.getAlgorithm());
			}
			Signature verification = Signature.getInstance(svParameter.getSignAlgorithm());
			verification.initVerify(publicKey);
			verify = new VerifyImp(verification, svParameter.getAlgorithm());
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public SVParameter getSVParameter() {
		// TODO Auto-generated method stub
		return svParameter;
	}

	@Override
	public byte[] getPublicKey() {
		// TODO Auto-generated method stub
		return publicKey.getEncoded();
	}

	@Override
	public byte[] getPrivateKey() {
		// TODO Auto-generated method stub
		return privateKey.getEncoded();
	}

	@Override
	public Sign getSign() {
		// TODO Auto-generated method stub
		return sign;
	}

	@Override
	public Verify getVerify() {
		// TODO Auto-generated method stub
		return verify;
	}

	@Override
	public void setParams(Parameters parameter) {
		// TODO Auto-generated method stub
		svParameter = (SVParameter) parameter;
	}
}
